package com.ciaojian.store.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ciaojian.core.mapper.FranchiseesMapper;
import com.ciaojian.core.model.Franchisees;
import com.ciaojian.core.model.vo.FranchiseesInfoVo;
import com.ciaojian.core.util.Result;
import com.ciaojian.core.util.SecretHelper;
import com.ciaojian.store.model.dto.FranchiseesDTO;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 * 加盟商 服务实现类
 * </p>
 *
 * @author Atlakyn
 * @since 2021-02-24
 */
@Service
public class FranchiseesServiceImpl extends ServiceImpl<FranchiseesMapper, Franchisees> {
    /**
     * 账号密码登录
     *
     * @param phone  账号
     * @param password 密码
     * @return 登录信息
     */
    public Franchisees loginByAccount(String phone, String password) {
        String encode = SecretHelper.encode(password);

        Franchisees franchisees = baseMapper.getByAccountAndPassword(phone);
        Assert.notNull(franchisees, "账号不存在");

        Assert.isTrue(encode.equals(franchisees.getPassword()), "账号或密码错误");
        franchisees.setPassword("");

        return franchisees;
    }

    /**
     * 账号密码注册
     *
     * @param phone  账号
     * @param password 密码
     * @return 登录信息
     */
    public Franchisees register(String phone, String password) {
        String encode = SecretHelper.encode(password);

        Franchisees franchiseesOld = baseMapper.getByAccountAndPassword(phone);
        if (ObjectUtil.isNotNull(franchiseesOld)) {
            Assert.notNull(franchiseesOld, "账号已存在");
        }

        Franchisees franchisees = new Franchisees();
        franchisees.setName("cano");
        franchisees.setPassword(encode);
        franchisees.insert();


        return franchisees;
    }


    /**
     * 登录业务
     *
     * @param phone  手机号
     * @param openId openId
     * @return 登录信息
     */
    public FranchiseesDTO login(String phone, String openId) {
        Franchisees franchisees = baseMapper.getByPhone(phone);
        Assert.notNull(franchisees, "手机号错误");
        return FranchiseesDTO.toFranchiseesDTO(franchisees);
    }

    public Result updateInfo(FranchiseesInfoVo franchiseesInfoVo) {
        Franchisees franchisees = new Franchisees().selectById(franchiseesInfoVo.getId());
        franchisees.setJoinPhoto(franchiseesInfoVo.getJoinPhoto());
        franchisees.setPhone(franchiseesInfoVo.getPhone());
        franchisees.updateById();
        return Result.ok(franchisees);
    }
}
